package data.collector;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 上海市住建委
 * 上海市建设市场信息服务平台
 * 现行标准
 */
public class ShanghaiZhujianweiStandard {

    //下载文件的附件的url
    public static String PAGE_URL = "https://ciac.zjw.sh.gov.cn/JGBStandardWeb/LR_Api/StandardReleaseApi/GetPageList";


    //下载文件的附件的url
    public static String DOWNLOAD_URL = "https://ciac.zjw.sh.gov.cn/JGBStandardWeb/LR_Api/StandardReleaseApi/GetFilePathByIdAndTypeNew?type=R0101&id=";

    //下载附件后的存储地址
    public static String DOWNLOAD_PATH = "E:\\dataset\\shzjwbz\\";

    public static void main(String[] args) {
        List<JSONObject> list = getPageResponse();
        downloadFile(list);
    }


    public static List<JSONObject> getPageResponse() {

        HashMap<String, Object> body = new HashMap<>();
        JSONObject pagination = new JSONObject();
        pagination.put("page", 1);

        //一共约500多条，一次性获取数据
        pagination.put("rows", 600);
        pagination.put("sord", "ASC");
        pagination.put("sidx", "S_CreateDate");

        JSONObject queryJson = new JSONObject();
        queryJson.put("type", 1);
        queryJson.put("S_Status", 1);
        queryJson.put("keyword", "");
        queryJson.put("S_Type", "");
        queryJson.put("FourType", 1);

        body.put("pagination", pagination.toJSONString());
        body.put("queryJson", queryJson.toJSONString());

        String response = HttpUtil.get(PAGE_URL, body);
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject.containsKey("data")) {
            JSONObject data = jsonObject.getJSONObject("data");
            if (data.containsKey("rows")) {
                return data.getJSONArray("rows").toList(JSONObject.class);
            }
        }
        return new ArrayList<>();
    }

    public static void downloadFile(List<JSONObject> list) {
        for (JSONObject item : list) {

            String filename = DOWNLOAD_PATH + item.getString("S_ProjectName") + ".pdf";
            if (FileUtil.exist(filename)) {
                continue;
            }

            //部分文件名不符合要求，需要修改
            if (item.getString("S_ProjectName").equals("1:500 1:1000 1:2000数字地形测绘标准")) {
                filename = "E:\\dataset\\shzjwbz\\数字地形测绘标准.pdf";
            }

            HttpUtil.downloadFile(getDownloadUrl(item.getString("S_ID")), filename);

            ThreadUtil.sleep(100);
        }
    }

    public static String getDownloadUrl(String uuid) {
        return DOWNLOAD_URL + uuid;
    }
}
